#include <cstdio>
#include <map>
#include <cstring>

using namespace std;

struct Line
{
    int x, y, z;
    Line( ) { }
    Line( int _x, int _y, int _z )
        : x( _x ), y( _y ), z( _z ) { }
};

bool operator < ( const Line &a, const Line &b )
{
    if ( a.x != b.x ) return a.x < b.x;
    if ( a.y != b.y ) return a.y < b.y;
    return a.z < b.z;
}

int n, m;
Line l[ 1001 ];

void work( )
{
    int i, j, x, y, z, t1, t2, ans = 0;
    char t, a, b;
    map<Line, int> mp;
    map<Line, int> ml;
    for ( i = 0; i < m; i++ )
    {
        scanf("%c", &t);
        scanf("%c=%d,%c=%d", &a, &t1, &b, &t2);
        x = y = z = 0;
        switch( a )
        {
            case 'X': x = t1; break;
            case 'Y': y = t1; break;
            case 'Z': z = t1; break;
        }
        switch( b )
        {
            case 'X': x = t2; break;
            case 'Y': y = t2; break;
            case 'Z': z = t2; break;
        }
        if ( t1 <= 0 || t1 > n || t2 <= 0 || t2 > n ) { l[ i ] = Line( 0, 0, 0 ); continue; }
        mp.clear( );
        if ( a == 'X' && b == 'Y' || a == 'Y' && b == 'X' )
        {
            if ( ml[ Line( x, y, z ) ] ) { l[ i ] = Line( 0, 0, 0 ); continue; }
            ans += n;
            for ( j = 0; j < i; j++ )
            {
                if ( !l[ j ].z ) continue;
                if ( ( l[ j ].y == y || l[ j ].x == x ) && !mp[ Line( x, y, l[ j ].z ) ] )
                {
                    ans--;
                    mp[ Line( x, y, l[ j ].z ) ] = 1;
                }
            }
        }
        if ( a == 'X' && b == 'Z' || a == 'Z' && b == 'X' )
        {
            if ( ml[ Line( x, y, z ) ] ) { l[ i ] = Line( 0, 0, 0 ); continue; }
            ans += n;
            for ( j = 0; j < i; j++ )
            {
                if ( !l[ j ].y ) continue;
                if ( ( l[ j ].x == x || l[ j ].z == z ) && !mp[ Line( x, l[ j ].y, z ) ] )
                {
                    ans--;
                    mp[ Line( x, l[ j ].y, z ) ] = 1;
                }
            }
        }
        if ( a == 'Y' && b == 'Z' || a == 'Z' && b == 'Y' )
        {
            if ( ml[ Line( x, y, z ) ] ) { l[ i ] = Line( 0, 0, 0 ); continue; }
            ans += n;
            for ( j = 0; j < i; j++ )
            {
                if ( !l[ j ].x ) continue;
                if ( ( l[ j ].y == y || l[ j ].z == z ) && !mp[ Line( l[ j ].x, y, z ) ] )
                {
                    ans--;
                    mp[ Line( l[ j ].x, y, z ) ] = 1;
                }
            }
        }
        l[ i ] = Line( x, y, z );
        ml[ l[ i ] ] = 1;
    }
    printf("%d\n", ans);
}

int main( )
{
    int t;
    scanf("%d", &t);
    while ( t-- )
    {
        scanf("%d%d", &n, &m);
        work( );
    }
    return 0;
}
